package insta.project.remote;

import java.util.ArrayList;
import java.util.List;

import insta.project.player.Audio;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * Database adapter object
 * 
 * @author Eric Alexis
 * 
 */
public class RemoteAudioFactory {
	private SQLiteDatabase _sqlDatabase;
	private BDDOpenHelper _dboOpenHelper;

	/**
	 * Constructor - Initializes helper
	 * 
	 * @param context
	 */
	public RemoteAudioFactory(Context context) {
		BDDOpenHelper _dboHelper = new BDDOpenHelper(context,
				BDDOpenHelper.NOM_BDD, null, BDDOpenHelper.VERSION_BDD);
		this._dboOpenHelper = _dboHelper;

		this.forceRequest();
		try {
			this.updgradeAudioList();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void forceRequest() {
		open();
		String request = "SELECT " + BDDOpenHelper._COL_AUDIO_ID + " FROM "
				+ BDDOpenHelper.TABLE_MUSIC;
		Cursor c = _sqlDatabase.rawQuery(request, null);
		c.close();
		close();

	}

	/**
	 * Opens database object
	 */
	public void open() {
		_sqlDatabase = _dboOpenHelper.getWritableDatabase();
	}

	/*
	 * Closes database object
	 */
	public void close() {
		_sqlDatabase.close();
	}

	/**
	 * Returns database object
	 * 
	 * @return
	 */
	public SQLiteDatabase getBDD() {
		return _sqlDatabase;
	}

	public boolean updgradeAudioList() throws Exception {
		boolean bSomethingUpdated = false;
		if (this._dboOpenHelper.isServiceUp()) {
			/**
			 * Get whole audio list from database
			 */
			open();
			String request = "SELECT " + BDDOpenHelper.COL_AUDIO_ID + " FROM "
					+ BDDOpenHelper.TABLE_MUSIC;
			List<Integer> lsExistingIdList = new ArrayList<Integer>();
			Cursor c = _sqlDatabase.rawQuery(request, null);
			if (c.getCount() > 0) {
				lsExistingIdList.add(BDDOpenHelper._COL_AUDIO_ID);
			}

			/*
			 * Now, get full list from freebangers.com
			 */
			String[][] strRemoteMusicData = HttpRequest.getInstance()
					.getMusicListArray();
			long lgCurrentUpdate = System.currentTimeMillis();
			for (int i = 0; i < strRemoteMusicData.length; i++) {
				if (!lsExistingIdList.contains(Integer
						.parseInt(strRemoteMusicData[i][4]))) {
					String[] musicData = strRemoteMusicData[i];
					if (musicData.length == 5 && musicData[0] != null
							&& musicData[1] != null && musicData[2] != null
							&& musicData[3] != null && musicData[4] != null) {
						request = "INSERT INTO " + BDDOpenHelper.TABLE_MUSIC
								+ "(" + BDDOpenHelper.COL_AUDIO_ID + ", "
								+ BDDOpenHelper.COL_TITLE + ", "
								+ BDDOpenHelper.COL_ARTIST + ", "
								+ BDDOpenHelper.COL_FILENAME + ", "
								+ BDDOpenHelper.COL_IMAGEURI + " , "
								+ BDDOpenHelper.COL_DATEINSERT + ") VALUES (\""
								+ musicData[4] + "\", \"" + musicData[0]
								+ "\", \"" + musicData[1] + "\",\""
								+ musicData[2]
								+ "\",\"http://www.freebangers.com/__files/"
								+ musicData[3] + "\", " + lgCurrentUpdate + ")";
						_sqlDatabase.rawQuery(request, null);
						bSomethingUpdated = true;
					}
				}
			}
			c.close();
			close();

		}
		return bSomethingUpdated;
	}

	public List<Audio> getAudioList() {
		open();
		List<Audio> lstAudioFromDatabase = new ArrayList<Audio>();
		String request = "SELECT * FROM " + BDDOpenHelper.TABLE_MUSIC;
		Cursor c = _sqlDatabase.rawQuery(request, null);
		if (c.getCount() > 0) {
			while (c.moveToNext()) {
				lstAudioFromDatabase.add(this.cursorToAudio(c));
			}
		}
		c.close();
		// Here, cursor found no audio list
		close();
		return lstAudioFromDatabase;
	}

	/*
	 * Method to convert cursor to departement object
	 * 
	 * @param c - The cursor you want to convert into a departement object
	 * 
	 * @return
	 */
	public Audio cursorToAudio(Cursor c) {
		Audio _newAudio = new Audio();
		int nIdResult = c.getInt(BDDOpenHelper._COL_AUDIO_ID);
		String strTitle = c.getString(BDDOpenHelper._COL_TITLE);
		String strArtist = c.getString(BDDOpenHelper._COL_ARTIST);
		String strFileName = c.getString(BDDOpenHelper._COL_FILENAME);
		String strImageUri = c.getString(BDDOpenHelper._COL_IMAGEURI);
		// Set our values into the departement object
		_newAudio = new Audio(strTitle, strArtist, strFileName, strImageUri,
				nIdResult);
		_newAudio.setAudio_id(nIdResult);
		return _newAudio;
	}

}
